package com.bwie.servicemodule.adapter;

import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.bwie.servicemodule.controler.GlideControler;

import java.util.ArrayList;
import java.util.List;

public abstract class UniversalRecyclerAdapter<T> extends RecyclerView.Adapter<RecyclerViewHolder> {

    // 数据源
    private List<T> list = new ArrayList<>(  );
    // 加载的布局
    private int layoutID;
    // 点击事件
    private OnRecyclerViewItemListener onRecyclerViewItemListener;

    // 点击事件
    public void setOnRecyclerViewItemListener(OnRecyclerViewItemListener onRecyclerViewItemListener) {
        this.onRecyclerViewItemListener = onRecyclerViewItemListener;
    }

    // 构造
    public UniversalRecyclerAdapter(int layoutID) {
        this.layoutID = layoutID;
    }

    // 发送数据源
    public void setList(List<T> list) {
        this.list.addAll( list );
        notifyDataSetChanged();
    }

    public void setClear() {
        this.list.clear();
    }

    public T getRecyclerItem( int position ) {
        return list.get( position );
    }

    @NonNull
    @Override
    public RecyclerViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        return new RecyclerViewHolder( LayoutInflater.from( viewGroup.getContext() ).inflate( layoutID, viewGroup, false ), viewGroup.getContext());
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerViewHolder viewHolder, final int i) {

        loadDate( viewHolder, list.get( i ) );

        if( onRecyclerViewItemListener != null) {
            viewHolder.itemView.setOnClickListener( new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onRecyclerViewItemListener.onItemListener( UniversalRecyclerAdapter.this, viewHolder.itemView ,i );
                }
            } );
        }
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    // 加载数据源
    public abstract void loadDate( RecyclerViewHolder viewHolder, T data);

    /**
     * msg: 添加点击事件
     */
    public interface OnRecyclerViewItemListener  {
        void onItemListener( RecyclerView.Adapter adapter, View view ,int position);
    }
}
